package com.nuaa.shopping.service.impl;

import com.nuaa.shopping.constant.UserConstant;
import com.nuaa.shopping.dao.UserDao;
import com.nuaa.shopping.dao.impl.UserDaoImpl;
import com.nuaa.shopping.entity.User;
import com.nuaa.shopping.exception.UserDiabledException;
import com.nuaa.shopping.exception.UserNotFoundException;
import com.nuaa.shopping.exception.UsernameExistsException;
import com.nuaa.shopping.service.UserService;
import com.nuaa.shopping.util.MD5Util;

public class UserServiceImpl implements UserService {

	private UserDao userDao = new UserDaoImpl();

	@Override
	public void register(User user) throws UsernameExistsException {
		// 用户名不能与已存在的用户名相同
		User u = userDao.selectByUsername(user.getUsername());
		if(u != null){
			throw new UsernameExistsException("该用户名已存在!");
		}
		
		// 要对密码进行加密处理
		user.setPassword(MD5Util.encrypt(user.getPassword()));

		// 设置用户状态默认为启用
		user.setStatus(UserConstant.USER_STATUS_ENABLE);
		
		userDao.insert(user);
	}


	@Override
	public User login(User user) throws UserNotFoundException, UserDiabledException {
		// 对密码进行加密处理
		user.setPassword(MD5Util.encrypt(user.getPassword()));
		
		User u = userDao.selectByUsernameAndPassword(user);
		if(u==null){
			throw new UserNotFoundException("用户名或密码不正确！");
		}
		if(u.getStatus() == UserConstant.USER_STATUS_DISABLE){
			throw new UserDiabledException("用户被锁定！");
		}
		return u;
	}

}
